<template>
  <upload-excel :on-success="onSuccess" />
</template>
<script>
import { uploadEmployeesApi } from '@/api/employees'
// 处理天数的时间戳方法
import { formatExcelDate } from '@/utils/index'
export default {
  // 通过路由判断是哪个页面上传文件
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    onSuccess({ results }) {
      this.userUpload(results)
    },
    // 员工页面上传
    async userUpload(results) {
      if (this.type === 'user') {
        const list = this.formateData(results)
        await uploadEmployeesApi(list)
        this.$message.success('上传成功')
        this.$router.back()
      }
    },
    // 数据处理方法
    formateData(results) {
      const arr = []
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      results.forEach(item => {
        const obj = {}
        Object.keys(item).forEach(val => {
          // userRelations[val] => 所有的英文key
          const key = userRelations[val]

          // 判断日期是否是时间戳
          if (['timeOfEntry', 'correctionTime'].includes(key)) {
            // item[val] 返回数据中的值
            obj[key] = formatExcelDate(item[val])
          } else {
            obj[key] = item[val]
          }
        })
        arr.push(obj)
      })
      return arr
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
